<?php
/**
 * 框架初始包含
 * @author Yang
 * @version $Id$
 */

/**
 * @todo ini等环境的可配置，如时区，debug等
 * @todo 性能和debug模块的等待加入 
 */

// 编码
header("content-Type: text/html; charset=UTF-8");

// 定义框架路径
define('SF_PATH', dirname(__FILE__));

// 简写DIRECTORY_SEPARATOR
define('DS', DIRECTORY_SEPARATOR);

// GET请求过虑
if (preg_match('/[\"\']/', $_SERVER['REQUEST_URI'])) {
    quoteSecure($_GET);
}

// POST请求过虑
if ('POST' == $_SERVER['REQUEST_METHOD']) {
    quoteSecure($_POST);
}

// 注册自动加载
spl_autoload_register('autoload');


/**
 * 自动加载
 * new \SF\Db;
 */
function autoload ($class_name)
{
    if (substr($class_name, 0, 2) == 'SF') {
        $class_name = str_replace('\\', '/', $class_name);
        $class_file = SF_PATH . strstr($class_name, '/') .'.php';
        if (!is_file($class_file)) {
            throw new Exception($class_name . ' 对应的文件不存在：');
        }
        include_once $class_file;
    }
}


/**
 * 获取根路径 
 */
function getBaseUrl()
{
    static $base_url = null;
    if (null === $base_url) {
        $base_url = rtrim(dirname(getScriptUrl()), '\\/');
    }
    return $base_url;
}

/**
 * 获取脚本路径 
 */
function getScriptUrl()
{
    return isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : $_SERVER['PHP_SELF'];
}

/**
 * 获取IP
 * 如果有多个IP，只获取一个
 */
function getIp()
{
    if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR')) {
        $ip = getenv('REMOTE_ADDR');
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    if (true == ($p = strpos($ip, ','))) {
        $ip = substr($ip, 0, $p);
    }
    return $ip;
}

/**
 * addslashes
 * Key不允许出现引号
 */
function quoteSecure(&$var)
{
    if (!get_magic_quotes_gpc()) {
        if (is_array($var)) {
            foreach ($var as $key=>$value) {
                if (preg_match('/[\"\']/', $key)) {
                    unset($var[$key]);
                } elseif (preg_match('/[\"\']/', $value)) {
                    quoteSecure($var[$key]);
                }
            }
        } else {
            $var = addslashes($var);
        }
    }
}

/**
 * 获取REQUEST 
 */
function getRequest($key = null, $default = null, $filter = '')
{
    if (null === $key) {
        return array_merge(getGet(), getPost());
    }
    return isset($_POST[$key]) ? getPost($key, $default, $filter) : getGet($key, $default, $filter);
}

/**
 * 获取GET请求 
 */
function getGet($key = null, $default = null, $filter = '')
{
    if (null === $key) {
        return $_GET;
    }
    if (!isset($_GET[$key])) {
        return $default;
    }
    if ($filter) {
        return \SF\Filter::runFilter(trim($_GET[$key]), $filter);
    } else {
        return trim($_GET[$key]);
    }
}

/**
 * 获取POST请求 
 */
function getPost($key = null, $default = null, $filter = '')
{
    if (null === $key) {
        return $_POST;
    }
    if (!isset($_POST[$key])) {
        return $default;
    }
    if ($filter) {
        return \SF\Filter::runFilter($_POST[$key], $filter);
    } else {
        return $_POST[$key];
    }
}

/**
 * 寄存
 */
class Registry
{
    protected static $_pool = array();

    public static function set ($index, $value)
    {
        self::$_pool[$index] = $value;
    }

    public static function get ($index)
    {
        if (! self::isRegisted($index)) {
            throw new Exception('索引项`' . $index . '`不存在');
        }
        return self::$_pool[$index];
    }

    public static function isRegisted ($index)
    {
        return isset(self::$_pool[$index]);
    }
}


/**
 * 配置
 */
class Config
{
    // 容器
    protected static $_configs = array();

    /**
     * 添加配置，如果键值已存在则追加并同值覆盖
     * @param string|array $config
     */
    public static function set($key, $config)
    {
        self::$_configs[$key] = isset(self::$_configs[$key]) ? self::recursive_replace(self::$_configs[$key], $config) : $config;
    }

    /**
     * 递归覆盖同key的值
     */
    protected static function recursive_replace($org_val, $replace_val)
    {
        if (!is_array($org_val) || !is_array($replace_val)) {
            $org_val = $replace_val;
        } else {
            foreach ($replace_val as $key=>$item) {
                if (isset($org_val[$key]) && is_array($org_val[$key])) {
                    $org_val[$key] = self::recursive_replace($org_val[$key], $item);
                } else {
                    $org_val[$key] = $item;
                }
            }
        }
        return $org_val;
    }

    /**
     * 获取配置
     */
    public static function get($key, $default = null)
    {
        if (strpos($key, '.')) {
            $ks = explode('.', $key);
            $result = self::$_configs;
            foreach ($ks as $k) {
                if (isset($result[$k])) {
                    $result = $result[$k];
                } else {
                    $result = $default;
                    break;
                }
            }
        } else {
            $result = isset(self::$_configs[$key]) ? self::$_configs[$key] : $default;
        }
        return $result;
    }


    /**
     * 是否配置
     */
    public static function isExists($key)
    {
        return isset(self::$_configs[$key]);
    }
}
